package concurrency.multithreading;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-03-12 18:54
 **/
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);

        Thread thread1 = new TranslateThread("1st content", countDownLatch);
        Thread thread2 = new TranslateThread("2nd content", countDownLatch);
        Thread thread3 = new TranslateThread("3rd content", countDownLatch);
        System.out.println(countDownLatch.getCount());
        thread1.start();
        thread2.start();
        thread3.start();

        countDownLatch.await(10, TimeUnit.SECONDS);

        System.out.println("所有线程完成" + countDownLatch.getCount());
        // 给调用段返回翻译结果
    }
}

class TranslateThread extends Thread {
    private String content;
    private final CountDownLatch count;

    TranslateThread(String content, CountDownLatch count) {
        this.content = content;
        this.count = count;
    }


    @Override
    public void run() {
        // 在某些情况下, 执行的翻译解析, 抛出异常
        if (Math.random() > 0.5) {
            throw new RuntimeException("原文存在非法字符");
        }
        System.out.println(content + "的翻译已完成, 译文: ");
        count.countDown();
    }


}
